#!/usr/bin/python
# -*- coding: utf-8 -*-

import tornado.ioloop
import tornado.web
import os,time

class BaseHandler(tornado.web.RequestHandler):
    def get_argument_safe(self, arg_name):
        try:
            return self.get_argument(arg_name)
        except:
            return None

    def render_view(self, view_name):
            self.render('./view/'+view_name)

class CrudHandler(BaseHandler):
    def route(self):
        uris = self.request.uri.split('/')
        self.prj = uris[1]
        actions = uris[2].split('?')
        self.action_page = actions[0]
        self.action_name = self.action_page.split('.')[0]
        self.action_type = self.action_page.split('.')[1]

        action = getattr(self, self.action_name)

        action()

    def render_view_crud(self):
        self.render_view(self.prj + '/' + self.action_page)

    def index(self):
        self.render_view_crud()

    def lists(self):
        self.render_view_crud()

    def lists_detail(self):
        self.render_view_crud()

    def add(self):
        self.render_view_crud()

    def edit(self):
        self.render_view_crud()

    def show(self):
        self.render_view_crud()

    def save(self):
        self.finish({'message': 'ok'})

    def update(self):
        self.finish({'message': 'ok'})

    def delete(self):
        self.finish({'message': 'ok'})

    def search(self):
        self.finish({'message': 'ok'})

    def get(self,*args, **kwargs):
        self.route()

    def post(self,*args, **kwargs):
        self.route()

class MainHandler(BaseHandler):
    def get(self):
        self.render_view('index.html')


class BaseDomain(object):
    pass

class Demo(BaseDomain):
    def __init__(self):
        self.id = None
        self.name = None

    def func(self, a, b):
        pass

class DemoHandler(CrudHandler):
    pass

def make_app():
    ROOT = os.path.split(os.path.realpath(__file__))[0]

    return tornado.web.Application([
        (r"/js/(.*)", tornado.web.StaticFileHandler,         {"path": os.path.join(ROOT, 'js')}),
        (r"/css/(.*)", tornado.web.StaticFileHandler,         {"path": os.path.join(ROOT, 'css')}),
        (r"/image/(.*)", tornado.web.StaticFileHandler,         {"path": os.path.join(ROOT, 'image')}),
        (r"/images/(.*)", tornado.web.StaticFileHandler,         {"path": os.path.join(ROOT, 'images')}),
        (r"/fonts/(.*)", tornado.web.StaticFileHandler,         {"path": os.path.join(ROOT, 'fonts')}),
        (r"/", MainHandler),
        (r"/demo/(.*)", DemoHandler)
    ], debug=True)


APP_NAME = 'pyweb'
PORT = 8888
if __name__ == "__main__":
    print(APP_NAME)
    print('port:' + str(PORT))
    app = make_app()
    app.listen(PORT)
    try:
        tornado.ioloop.IOLoop.instance().start()
    except KeyboardInterrupt:
        tornado.ioloop.IOLoop.instance().stop()
